#include "IsometroicMap.h"

IsoMetricMap::IsoMetricMap():
	mpSprites(nullptr),
	mpTiles(nullptr),
	mNumSprites(0),
	mTileSizeW(0),
	mTileSizeH(0),
	mColumns(0),
	mRows(0)
{}
IsoMetricMap::~IsoMetricMap()
{}
void IsoMetricMap::Load(const char* pLevel, const char* pTexturePack)
{
	Unload();

	if(!LoadLevel(pLevel))
	{
		Unload();
		return;
	}
	else if(!LoadTexturePack(pTexturePack))
	{
		Unload();
		return;
	}
}
void IsoMetricMap::Unload()
{
	for(int i = 0; i < mNumSprites; ++i)
	{
		mpSprites[i].Unload();
	}
	delete [] mpSprites;
	delete [] mpTiles;
	mpTiles = nullptr;
	mTileSizeH = 0;
	mTileSizeW = 0;
	mColumns = 0;
	mRows = 0;
}
void IsoMetricMap::Update(float deltaTime)
{}
void IsoMetricMap::Render(const SVector2& viewOffset)
{
	for(int y = 0; y < mRows; ++y)
	{
		for(int x = 0; x < mColumns; ++x)
		{
			const int index = GetIndex2D(x, y);
			SVector2 pos((x-y) * mTileSizeW/2, (x+y)* mTileSizeH);
			SVector2 renderPosition = pos - viewOffset;
			mpSprites[mpTiles[index]].SetPosition(renderPosition);
			mpSprites[mpTiles[index]].Render();
		}
	}
}
bool IsoMetricMap::LoadLevel(const char* pLevel)
{
	FILE * pFile(nullptr);
	fopen_s(&pFile, pLevel, "r");
	if(pFile == nullptr)
	{
		return false;
	}
	else
	{
		fscanf_s(pFile, "%*s %d", &mTileSizeH);
		fscanf_s(pFile, "%*s %d", &mTileSizeW);
		fscanf_s(pFile, "%*s %d", &mColumns);
		fscanf_s(pFile, "%*s %d", &mRows);
		mpTiles = new int[mColumns*mRows];

		fgetc(pFile);
		for(int y = 0; y< mRows; ++y)
		{
			for(int x = 0; x < mColumns; ++x)
			{
				const int index = GetIndex2D(x,y);
				mpTiles[index] = fgetc(pFile) - '0';
			}
		}
		fgetc(pFile);
	}
	fclose(pFile);
	return true;
}
bool IsoMetricMap::LoadTexturePack(const char* pTexturePack)
{
	FILE* pFile = nullptr;

	fopen_s(&pFile, pTexturePack, "r");
	if(pFile == nullptr)
	{
		return false;
	}
	else
	{
		fscanf_s(pFile, "%*s %d", &mNumSprites);
		mpSprites = new SGE_Sprite[mNumSprites];

		char buffer[256];
		for(int i = 0; i < mNumSprites; ++i)
		{
			fscanf_s(pFile, "%s", buffer, 256);
			mpSprites[i].Load(buffer);
		}
	}
	fclose(pFile);
	return true;
}
int IsoMetricMap::GetIndex2D(int x, int y) const
{
	return x + (y * mColumns);
}